// SqlGutterIconProvider.java
package org.example.batch;

import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.LineMarkerProvider;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.psi.PsiElement;
import com.intellij.psi.xml.XmlText;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.util.PsiTreeUtil;
import org.example.demo.SqlValidator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Collection;
import java.util.List;

public class SqlGutterIconProvider implements LineMarkerProvider {

    @Override
    public LineMarkerInfo<?> getLineMarkerInfo(@NotNull PsiElement element) {
        if (!(element instanceof XmlText)) return null;

        XmlText xmlText = (XmlText) element;
        XmlTag tag = PsiTreeUtil.getParentOfType(xmlText, XmlTag.class);
        if (tag == null || !isSqlTag(tag.getName())) return null;

        String sql = xmlText.getValue().trim();
        if (sql.isEmpty()) return null;

        String error = SqlValidator.validate(sql);
        Icon icon = error == null ? AllIcons.General.InspectionsOK : AllIcons.General.Error;

        return new LineMarkerInfo<>(
                xmlText,
                xmlText.getTextRange(),
                icon,
                e -> error == null ? "SQL 语法正确" : "SQL 错误: " + error,
                null,
                GutterIconRenderer.Alignment.RIGHT
        );
    }

    @Override
    public void collectSlowLineMarkers(@NotNull List<? extends PsiElement> elements,
                                       @NotNull Collection<? super LineMarkerInfo<?>> result) {
        // 可留空，或批量处理（可选优化）
    }

    private boolean isSqlTag(String tagName) {
        return "select".equalsIgnoreCase(tagName) ||
               "update".equalsIgnoreCase(tagName) ||
               "insert".equalsIgnoreCase(tagName) ||
               "delete".equalsIgnoreCase(tagName);
    }
}